package com.hexinfo.dmpro.monitor.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hexinfo.dmpro.common.utils.StringUtils;
import com.hexinfo.dmpro.monitor.model.ImpalaAppModel;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import com.hexinfo.dmpro.monitor.model.base.MonitorRsp;
import org.joda.time.DateTime;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author peng
 * @date 2022/2/15 15:18
 */
@Slf4j
@Service
public class CmImpalaAppService {

    private int SUCESS_CODE = 200;

    @Autowired
    private CmApiService cmApiService;

    //监控QUERY、DML、DDL类型的impala语句，查询1000条
    private String apiUrl = "/clusters/{clusterName}/services/{serviceName}/impalaQueries?filter=(queryType=QUERY or queryType=DML or queryType=DDL)&limit=1000&from={startTime}";

    public List<ImpalaAppModel> getImpalaApps(MonitorReq req) {
        List<ImpalaAppModel> impalaAppModels = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(req.getOtherParam());
        //配置cm Api的 url
        String url = jsonObject.get("cmApi").toString();
        req.setUrl(url);
            String user = jsonObject.get("user").toString();
        String password = jsonObject.get("password").toString();

        Map header = new HashMap<>();
        try {
            header.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")));
            req.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            log.error("设置Authorization异常", e);
        }
        JSONArray jsonArray = null;
        url += apiUrl;
        String startTime = req.getStartTime();
        startTime = getISO86Time(startTime);
        req.setUrl(url.replace("{clusterName}", req.getClusterFlag()).replace("{startTime}",startTime).replace("{serviceName}",req.getServiceName()));
        MonitorRsp rsp = cmApiService.execute(req);
        if (SUCESS_CODE == rsp.getCode()) {
            String body = rsp.getBody();
            JSONObject obj = JSONObject.parseObject(body);
            jsonArray = obj.getJSONArray("queries");
            if(jsonArray != null && jsonArray.size() >0){
                for(int i =0 ;i< jsonArray.size();i++){
                    JSONObject objApp = jsonArray.getJSONObject(i);
//                    //过滤DDL类型的 《use 库名》 语句
//                    JSONObject attributes = objApp.getJSONObject("attributes");
//                    String ddl_type = attributes.getString("ddl_type");
//                    if("DDL".equalsIgnoreCase(objApp.getString("queryType")) && "USE".equalsIgnoreCase(ddl_type)){
//                        continue;
//                    }
                    ImpalaAppModel impalaAppModel = new ImpalaAppModel();

                    impalaAppModel.setAppId(objApp.getString("queryId"));
                    impalaAppModel.setStartTime(getBjTime(objApp.getString("startTime")));
                    if(objApp.get("endTime")!=null){
                        impalaAppModel.setEndTime(getBjTime(objApp.getString("endTime")));
                    }
                    if(objApp.get("attributes")!=null){
                        impalaAppModel.setHostId(objApp.getJSONObject("attributes").getString("network_address").replace("::ffff:",""));
                    }
                    impalaAppModel.setState(objApp.getString("queryState"));
                    impalaAppModel.setUser(objApp.getString("user"));
                    impalaAppModel.setDbName(objApp.getString("database"));
                    impalaAppModel.setImpalaSql(objApp.getString("statement"));
                    impalaAppModel.setQueryType(objApp.getString("queryType"));
                    impalaAppModel.setWaitingTime(null);
                    impalaAppModel.setDuration(objApp.getLong("durationMillis")+"");
                    impalaAppModel.setScanProgress(null);
                    impalaAppModel.setState(objApp.getString("queryState"));
                    impalaAppModel.setResourcePool(objApp.getJSONObject("attributes").getString("pool"));
                    impalaAppModel.setRowsFetched(objApp.getString("rowsProduced"));
                    impalaAppModels.add(impalaAppModel);
                }
            }
        }
        return impalaAppModels;
    }

    public static String getISO86Time(String date) {
        if (StringUtils.isBlank(date)) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newTime = null;
        try {
            newTime = format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        TimeZone tz = TimeZone.getTimeZone("GMT-01");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(tz);
        return df.format(newTime);
    }

    public static String getBjTime(String ISOdate) {
        if (StringUtils.isBlank(ISOdate)) {
            return "";
        }
        DateTimeFormatter dtf1 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        DateTime dt = dtf1.parseDateTime(ISOdate);
        DateTimeFormatter dtf2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        return dt.toString(dtf2);
    }
}
